package ua.kpi.flats.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ua.kpi.flats.dao.ClientDao;
import ua.kpi.flats.entity.Client;
import ua.kpi.flats.service.ClientService;

@Service("clientService")
public class ClientServiceImpl implements ClientService {
	private Logger logger = LoggerFactory.getLogger(ClientServiceImpl.class);
	private ClientDao clientDao;
	
	@Override
	@Transactional(readOnly = true,
			       propagation = Propagation.REQUIRES_NEW)
	public Map<String,Object> getClients(int from, int limit) {		
		try {
			Map<String,Object> result = new HashMap<String,Object>();
			result.put("clients", clientDao.getClients(from, limit));
			result.put("count", clientDao.count());
			return result;
		} catch (DataAccessException e) {
			logger.error("Error while loading clients from " + from + ",count " + limit, e);
			return null;
		}		
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public Map<String,Object> add(Client client) {
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("success", true);
		try {			
			boolean contains = clientDao.contains(client);
			result.put("contains", contains);
			if (!contains) {
				clientDao.add(client);
				result.put("client", client);
				result.put("added", true);
			} 
		} catch (DataAccessException e) {
			result.put("added", false);
			logger.error("Cant add client " + client, e);			
		}
		return result;
	}
	
	@Autowired
	public void setClientDao(ClientDao clientDao) {
		this.clientDao = clientDao;
	}
}
